<template>
  <scroll-view
    style="height: 100vh; width: 100vw"
    :style="customStyle"
    :scroll-y="!disabled"
    v-if="isScrollView"
    @scroll="scrolls"
    :scroll-top="scrollTop"
    :enhanced="true"
    :show-scrollbar="false"
    :bounces="false"
    :lower-threshold="lowerThreshold"
    @scrolltolower="$u.throttle(scrollBt, 1000)"
  >
    <slot></slot>
  </scroll-view>
  <view :style="[$u.addStyle(customStyle)]" v-else>
    <slot></slot>
  </view>
</template>

<script setup>
// 防止频繁更新视图
let realScrollTop = {}

const props = defineProps({
  /**
   * ui-page-scroll 页面使用scroll-view滚动
   * @description 页面使用scroll-view滚动
   * @property {Boolean}	isScrollView 是否开启滚动
   * @property {Boolean}	disabled 禁用滚动
   * @property {Object} customStyle 定义需要用到的外部样式
   * @property {Object} customClass 类名
   * @event {Function} scroll	滚动
   */
  isScrollView: {
    type: Boolean,
    default: false
  },
  lowerThreshold: {
    type: Number,
    default: 50
  },
  disabled: {
    type: Boolean,
    default: false
  },
  // 每个组件都有的父组件传递的样式，可以为字符串或者对象形式
  customStyle: {
    type: [Object, String],
    default: () => ({})
  },
  customClass: {
    type: String,
    default: ''
  }
})

const uid = ref(Math.random().toString(36).substr(2))

const scrollTop = ref(0)
const scrollTo = (y) => {
  scrollTop.value = realScrollTop[this.uid] || 0
  nextTick(() => {
    scrollTop.value = y
  })
}

const scrolls = (evt) => {
  realScrollTop[uid.value] = evt.detail.scrollTop
  this.$emit('scrolls', evt)
}
const scrollBt = () => {
  this.$emit('scrollBt')
}
const addUnit = (value, unit) => {
  return this.$ui.addUnit(value, unit)
}

onBeforeUnmount(() => {
  delete realScrollTop[uid.value]
})
</script>

<style lang="scss"></style>
